import * as THREE from '../../build/three.module.js';
import Stats from '../../jsm/libs/stats.module.js';
import { GUI } from '../../jsm/libs/dat.gui.module.js';

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x050505);

const camera = new THREE.PerspectiveCamera(65, innerWidth / innerHeight, 1, 10000);
camera.position.z = 64;

const light = new THREE.HemisphereLight();
scene.add(light);

const gmt = new THREE.BufferGeometry(),
      indices = [], // 指数
      vertices = [], // 顶点
      normals = [], // 发现
      colors = [], // 颜色
      size = 20, // 尺寸
      segments = 10, // 分片数
      halfSize = size / 2,
      segmentSize = size / segments; // 每个分片尺寸

// 生成一个简单网格几何体顶点、发现和颜色数据
for(let i = 0; i <= segments; i += 1) {
  const y = (i * segmentSize) - halfSize; // [-10, 10];
  for(let j = 0; j <= segments; j += 1) {
    const x = (j * segmentSize) - halfSize; // [-10, 10];
    vertices.push(x, y, 0);
    normals.push(0, 0, 1);
    const r = (x / size) + .5; // [0, -1]
    const g = (y / size) + .5;
    colors.push(r, g, 1);
  }
}

// 生成顶点索引
for(let i = 0; i < segments; i += 1) {
  for(let j = 0;j < segments; j += 1) {
    const a = i * (segments + 1) + (j + 1);
    const b = i * (segments + 1) + j;
    const c = (i + 1) * (segments + 1) + j;
    const d = (i + 1) * (segments + 1) + (j + 1);
    indices.push(a, b, d);
    indices.push(b, c, d); // 定义相邻两个面共用两个顶点
  }
}

gmt.setIndex(indices);
gmt.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
gmt.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3));
gmt.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));

const mtl = new THREE.MeshPhongMaterial({
  vertexColors: THREE.VertexColors,
  side: THREE.DoubleSide
});

const mesh = new THREE.Mesh(gmt, mtl);
scene.add(mesh);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const stats = new Stats();

const gui = new GUI();
gui.add(mtl, 'wireframe');

const render = () => {
  // const time = Date.now() * .001;
  // mesh.rotation.x = time * .25;
  // mesh.rotation.y = time * .5;
  
  renderer.render(scene, camera);
}

const animate = () => {
  requestAnimationFrame(animate);

  stats.update();
  render();
}
animate();

const handleWindowResize = () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(innerWidth, innerHeight);
}
window.addEventListener('resize', handleWindowResize, false);